<?php

/**
 * User controller handles the ajax requests from front-end
 *
 * @access 	public
 * @author      Rob
 * @copyright	ResMania 2009-present all rights reserved.
 * @version	1.0
 * @link	http://docs.resmania.com/index.php/LiveChat_Module
 * @since  	09-2010
 */
class RM_User_LiveChatController extends RM_Controller {

    /**
     * calls the front-end main template file
     */
    public function chatAction() {
        ob_clean();

        // call the view
        echo $this->view->render('LiveChat/chat.phtml');
        die();
    }

    /**
     * gets updates to the the chat conversation.
     * This is the main process that is called by the JS timer process
     * and runs reguarly. This should be lightweight so it is quick and
     * returns only a small amount of data.
     *
     * @return json
     */
    public function dialogueJsonAction() {

        $chat_id = $this->_getParam('chat_id');

        // chat info
        $dao = new RM_LiveChat();
        $chatInfo = $dao->fetchAll($chat_id)->toArray();

        $daoDialogue = new RM_LiveChatDialogue();
        $rows = $daoDialogue->getDialogue($chat_id, false)->toArray();

        // update the sent marker
        foreach ($rows as $row) {
            $daoDialogue->acknowledgeMessage($row['id'], false);
        }

        $json = new stdClass;
        $json->chatInfo = $chatInfo;
        $json->data = $rows;

        // update the user istyping status
        $userIsTyping = (int)$this->_getParam('isTyping');
        $dao->setIsTyping($chat_id,false,$userIsTyping);

        // get if the operator is type
        $adminIsTyping = $dao->getIsTyping(true,$chat_id)->toArray();
        $json->isTyping = $adminIsTyping[0]['operator_istyping'];
        
        echo Zend_Json::encode($json);
        die;
    }

    /**
     * Sends the message to the server
     *
     * @return json
     */
    public function sendmessageJsonAction() {

        $chat_id = $this->_getParam('chat_id');
        $message = $this->_getParam('message');
        $timestamp = $this->_getParam('timestamp');

        // TODO: check message for bad things

        $chatData['chat_id'] = $chat_id;
        $chatData['user'] = $message;
        $chatData['datetime'] = $timestamp;

        // update the livechat lastupdate row, this is used to prune old messages
        $dao = new RM_LiveChat();
        $dao->updateLastUpdate($chat_id);

        // insert it to the db...
        $daoDialogue = new RM_LiveChatDialogue();
        $result = $daoDialogue->insert($chatData);
    }

    /**
     * checks if there is an operator available/online
     */
    public function checkavailableJsonAction() {
        $daoConfig = new RM_LiveChatConfig();
        $operatorInfo = $daoConfig->getStatus()->toArray();

        if (!empty($operatorInfo)){
            $operatorOnline = true;
        } else {
            $operatorOnline = false;
        }
        
        $json = new stdClass;
        $json->operator_online = $operatorOnline;

        echo Zend_Json::encode($json);
        die;
    }

    /**
     * sends a chat request to the server
     */
    public function requestchatJsonAction() {

        $chatData['id'] = $this->_getParam('chat_id');
        $chatData['user_name'] = $this->_getParam('name');
        $chatData['user_email'] = $this->_getParam('email');
        $chatData['ip'] = $this->_getParam('ip');
        $chatData['question'] = $this->_getParam('question');
        $chatData['operator_id'] = 0;
        $chatData['closed'] = 0;

        if ($this->_getParam('operatorStatus') == "true") {
            // save to db...
            $dao = new RM_LiveChat();
            $result = $dao->insert($chatData);

            if ($result) {
                echo Zend_Json::encode(array('data' => array('success' => true)));
                die;
            } else {
                echo Zend_Json::encode(array('data' => array('success' => false)));
                die;
            }
        } else {

            // email the question to the the system admin
            $mailer = new RM_Module_Emailnotifications();
            $result = $mailer->AdminNotify($chatData['user_email'], $chatData['user_name'], "LiveChat Question", $chatData['question']);
            if ($result) {
                echo Zend_Json::encode(array('data' => array('success' => true)));
                die;
            } else {
                echo Zend_Json::encode(array('data' => array('success' => false)));
                die;
            }
        }

        echo Zend_Json::encode($json);
        die;
    }

    /**
     * closes a chat
     *
     * @return json
     */
    public function closechatJsonAction() {

        $chat_id = $this->_getParam('chat_id');
        $dao = new RM_LiveChat();
        $result = $dao->closeChat($chat_id);

        return array('data' => array(
                'success' => true
        ));
    }

    /**
     * cancels a chat
     */
    public function cancelrequestJson() {
        $chat_id = $this->_getParam('chat_id');

        $dao = new RM_LiveChat();
        $dao->delete($chat_id);
    }

}